import { requestWithAuth } from "./request";
import { ElMessage } from "element-plus";
import cache from "@/utils/cache";

const CACHE_KEY = {
  BRAND_LIST: "brand_list",
  BRAND_DETAIL: "brand_detail_",
};

const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

/**
 * 统一的错误处理
 * @param {Error} error - 错误对象
 * @param {string} customMessage - 自定义错误消息
 */
const handleError = (error, customMessage = "操作失败") => {
  console.error(error);
  ElMessage.error(customMessage);
  throw error;
};

/**
 * 获取品牌列表
 * @returns {Promise} - 返回品牌列表数据
 */
export async function getBrands() {
  try {
    const response = await requestWithAuth({
      url: "/Brand/list",
      method: "get",
    });

    // 确保返回的是数组
    const brands = Array.isArray(response.data.data) ? response.data.data : [];
    return { data: brands };
  } catch (error) {
    handleError(error, "获取品牌列表失败");
    return { data: [] }; // 发生错误时返回空数组
  }
}

/**
 * 获取单个品牌信息
 * @param {number} id - 品牌ID
 * @returns {Promise} - 返回品牌信息
 */
export async function getBrand(id) {
  try {
    if (!id) throw new Error("品牌ID不能为空");

    // 检查缓存
    const cacheKey = `${CACHE_KEY.BRAND_DETAIL}${id}`;
    const cachedData = cache.get(cacheKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await requestWithAuth({
      url: `/Brand/detail/${id}`,
      method: "get",
    });

    cache.set(cacheKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取品牌详情失败");
  }
}

/**
 * 创建新品牌
 * @param {Object} brandData - 新品牌的数据
 * @returns {Promise} - 返回创建操作的结果
 */
export const createBrand = async (brandData) => {
  try {
    if (!brandData.name) {
      throw new Error("品牌名称不能为空");
    }

    const response = await requestWithAuth({
      url: "/Brand/create",
      method: "POST",
      data: brandData,
    });

    // 清除列表缓存
    cache.removeByPrefix(CACHE_KEY.BRAND_LIST);

    return response;
  } catch (error) {
    handleError(error, "创建品牌失败");
  }
};

/**
 * 更新品牌信息
 * @param {Object} brandData - 更新的品牌数据
 * @returns {Promise} - 返回更新操作的结果
 */
export const updateBrand = async (brandData) => {
  try {
    if (!brandData.id) {
      throw new Error("品牌ID不能为空");
    }
    if (!brandData.name) {
      throw new Error("品牌名称不能为空");
    }

    const response = await requestWithAuth({
      url: `/Brand/update/${brandData.id}`,
      method: "PUT",
      data: brandData,
    });

    // 清除相关缓存
    cache.removeByPrefix(CACHE_KEY.BRAND_LIST);
    cache.remove(`${CACHE_KEY.BRAND_DETAIL}${brandData.id}`);

    return response;
  } catch (error) {
    handleError(error, "更新品牌信息失败");
  }
};

/**
 * 删除品牌
 * @param {number} id - 要删除的品牌ID
 * @returns {Promise} - 返回删除操作的结果
 */
export const deleteBrand = async (id) => {
  try {
    if (!id) throw new Error("品牌ID不能为空");

    const response = await requestWithAuth({
      url: `/Brand/delete/${id}`,
      method: "DELETE",
    });

    // 清除相关缓存
    cache.removeByPrefix(CACHE_KEY.BRAND_LIST);
    cache.remove(`${CACHE_KEY.BRAND_DETAIL}${id}`);

    return response;
  } catch (error) {
    handleError(error, "删除品牌失败");
  }
};
